# coding: UTF-8
# Filename : points_record_manage.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils
import time
import cPickle as p
from PointsInfo import *
from ScanInfo import *
record_file = utils.readFromIni('record_data')

operate_type_dict = {0:'其它',1:'商品',2:'分店',3:'企业',4:'系统操作'}
points_type_dict = {0:'系统操作',1:'签到',2:'评论',3:'分享',4:'登陆',5:'审核通过'}

#增加积分
def update_points(user_id, cus_id, scores):
    #增加积分
    update__sql = 'update member set total_score = total_score + %s, curr_score = curr_score + %s where user_id = %s and cus_id = %s'
    rst = mysql.update(update__sql, [scores, scores, user_id, cus_id])
    #确定是否升级会员
    get_member_level_sql = 'select level, total_score from member where user_id = %s'
    member_obj= mysql.get(get_member_level_sql, [user_id])
    if member_obj != None:
        level = member_obj[0]
        total_score = member_obj[1]
        get_level_sql = 'select upper_limit from member_level where cus_id = %s and level = %s'
        level_obj = mysql.get(get_level_sql, [cus_id, level])
        if level_obj != None:
            upper_limit = level_obj[0]
            #当前积分大于等于当前级别的积分上限 则升级
            if total_score >= upper_limit:
                update__sql = 'update member set level = level + 1 where user_id = %s and cus_id = %s'
                rst = mysql.update(update__sql, [user_id, cus_id])
    return rst

#查询某积分维度
def get_points_dimensionality(user_id, cus_id, column):
    
    get_scores_sql = 'select %s from points_conf ' % column
    get_scores_sql = get_scores_sql + ' where cus_id = %s'
    scores_obj = mysql.get(get_scores_sql, [cus_id])
    if scores_obj == None or len(scores_obj) == 0: return
    scores = scores_obj[0]
    return scores

#获取评论 签到  分享 积分维度
def get_css_dimensionality(type, cus_id):
    #周期单位字典
    dict = {0:1, 1:60, 2:3600, 3:3600*24, 4:3600*24*7, 5:3600*24*30, 6:3600*24*365}
    common_sql = '''select %s_increment_points, %s_valid_period, %s_period_measure,
    %s_period_times from points_conf ''' % (type, type, type, type)
    common_sql +=  'where cus_id = %s'
    obj = mysql.get(common_sql, [cus_id])
    if obj == None or len(obj) == 0 : return (None, None, None)
    increment_points = obj[0]
    valid_period = obj[1]
    period_measure = obj[2]
    period_times = obj[3]
    #(时间,次数,分数)
    return (valid_period * dict[period_measure], period_times, increment_points)

#存储对象到文件
def store_obj(obj):
    f = file(record_file, 'w')
    p.dump(obj, f)
    f.close()

#获得存储文件中数据
def get_obj():
    f = file(record_file)
    obj = p.load(f)
    f.close()
    return obj

#检测在规定时间内是否已经增加过积分
def check_is_ok(user_id, cus_id, type, time_limit_allowed, allowed_count, obj_id = ''):
    flag = True
    dict_key = str(user_id) + '_' + str(cus_id) + '_' + str(obj_id) + type
    now = int(time.time())
    dict_obj = get_obj()
    if isinstance(dict_obj, dict):
        if dict_obj.has_key(dict_key):
            value_obj = dict_obj[dict_key]
            last_time = value_obj[0]
            count = value_obj[1]
            time_limit = now - last_time
            #时间小于允许时间
            if time_limit < time_limit_allowed:
                #运行次数大于允许次数
                if allowed_count <= count:
                    flag = False
                else:
                   dict_obj[dict_key] = (last_time, count+1)
                   store_obj(dict_obj)
            #时间超出允许时间 就初始化
            else:
                dict_obj[dict_key] = (now, 1)
                store_obj(dict_obj)
        #没有记录则做初始化
        else:
           dict_obj[dict_key] = (now, 1)
           store_obj(dict_obj)
    return flag

#插入积分记录逻辑
def insert_points_record(cus_id, user_id, obj_id, points_type, operate_type, scores, add_or_subtraction):
    member_id_sql = 'select id, number, level from member where cus_id = %s and user_id = %s'
    insert_points_record_sql = '''insert  into `points_record` 
        (`cus_id`, `member_id`, `card_num`, `level`, `operate_type`, `obj_id`, 
        `operate_time`, `points_type`, `add_or_subtraction`, `points_num`) 
        values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'''
    member_obj = mysql.get(member_id_sql, [cus_id, user_id])
    operate_time = int(time.time())
    rst = False
    if member_obj != None and len(member_obj) > 0:
        member_id = member_obj[0]
        card_number = member_obj[1]
        level = member_obj[2]
        param = [cus_id, member_id, card_number, level, operate_type, obj_id, operate_time, points_type, add_or_subtraction, scores]
        rst = mysql.insert(insert_points_record_sql, param)
    return rst

#登陆积分获取 表member 索引user_id cus_id
#为-1时表示 在规定时间内操作过频
def login_record(user_id, cus_id):
    #检查登陆频率 暂且是一天允许一次
    time_limit_allowed = 3600 * 60 * 24
    count = 1
    is_ok = check_is_ok(user_id, cus_id, 'login', time_limit_allowed, count)
    if not is_ok:
        return (is_ok, -1)
    
    #获取登陆积分维度
    login_scores = get_points_dimensionality(user_id, cus_id, 'use_app_points')
    #增加积分
    rst = update_points(user_id, cus_id, login_scores)
    
    #增加成功 增加积分记录
    if rst:
        insert_points_record(cus_id, user_id, 0, 4, 0, login_scores, 1)
    
    return (rst, login_scores)

#签到评论分享积分获取 type 表示区别date中的key
#type: share, comment
#obj_type = {0:'其它',1:'商品',2:'分店',3:'企业',4:'系统操作'}
#points_type = {0:'系统操作',1:'签到',2:'评论',3:'分享',4:'登陆',5:'审核通过'}
def record_css(user_id, cus_id, type, obj_type, points_type, obj_id):
    #(时间,次数,分数)
    (a,b,c) = get_css_dimensionality(type, cus_id)
    if a == None : return (False, 0)
    
    #判断是否在维度范围内
    rst = check_is_ok(user_id, cus_id, type, a, b, obj_id)
    if not rst : return (rst, -1)

    #增加积分 
    rst = update_points(user_id, cus_id, c)
    
    #增加积分成功 记录积分
    if rst:
        rst = insert_points_record(cus_id, user_id, obj_id, points_type, obj_type, c, 1)
    return (rst, c)

#积分列表
def get_points_list(user_id, cus_id, size, page_num):
    rst = []
    get_points_records_sql = '''select operate_type, obj_id, operate_time, points_type, points_num,
    points_desc, add_or_subtraction
    from points_record where cus_id = %s and member_id = (select tb2.id from member tb2 where tb2.user_id = %s) order by id desc limit %s, %s'''
    start_row = utils.get_star_row(size, page_num)
    param = [cus_id, user_id, int(start_row), int(size)]
    points_records_obj = mysql.doSearch(get_points_records_sql, param)
    if points_records_obj == None or len(points_records_obj) == 0: return None
    for obj in points_records_obj:
        p_record = PointsRecord()
        operate_type = obj[0]
        obj_id = obj[1]
        operate_time = obj[2]
        points_type = obj[3]
        points_num = obj[4]
        points_desc = obj[5]
        add_or_subtraction = obj[6]
        #数据模型分析建立view
        points_content = ''
        if points_type == 4:
            points_content = '登陆成功增加%s分' % points_num
        elif points_type == 5:
            points_content = '审核通过积分增加%s分' % points_num
        elif points_type == 0:
            points_content = points_desc
        else:
            points_content = '%s成功增加%s分' % (points_type_dict[points_type], points_num)
            
        p_record.points_num = points_num
        p_record.time_info = utils.get_time_between(operate_time)
        p_record.timetuple = operate_time
        p_record.points_content = points_content
        rst.append(p_record)
    
    return rst
        

#我的积分
def get_mypoints_info(user_id, cus_id, size):
    p_info = PointsInfo()
    #获取当前积分 和累计积分
    get_mem_obj_sql = '''select total_score, curr_score, level from member where user_id = %s and cus_id = %s '''
    mem_obj = mysql.get(get_mem_obj_sql, [user_id, cus_id])
    if mem_obj == None or len(mem_obj) == 0: return None
    total_score = mem_obj[0]
    curr_score = mem_obj[1]
    level = mem_obj[2]
    p_info.total_score = total_score
    p_info.curr_score = curr_score
    #获取alert信息
    get_next_level_sql = '''select name, lower_limit from member_level where level = %s and cus_id = %s'''
    next_level_obj = mysql.get(get_next_level_sql, [level+1, cus_id])
    if next_level_obj == None or len(next_level_obj) == 0: 
        alert_info = '您已经是最高级会员了'
    else:
        name = next_level_obj[0]
        lower_limit = next_level_obj[1]
        num_info = lower_limit - total_score
        alert_info = '还差%s分就可升级为%s了'
        alert_info = alert_info % (num_info, name)
    p_info.alert_info = alert_info
    
    #获取我的积分下面显示列表
    points_records = get_points_list(user_id, cus_id, size, 0)
    p_info.points_records = points_records
    
    return p_info


#扫码签到业务逻辑处理 返回-1表示规定时间内签到多次
def do_scan_signin(user_id, cus_id, chain_part_id):
    #(时间,次数,分数)
    type = 'signin'
    (a,b,c) = get_css_dimensionality(type, cus_id)
    if a == None : return (False, 0)
    
    #判断是否在维度范围内
    rst = check_is_ok(user_id, cus_id, type, a, b, chain_part_id)
    if not rst : return (rst, -1)
    
    #检测是否有此分店
    check_sql = 'select count(id) from chain_part where id = %s'
    check_obj = mysql.get(check_sql, [chain_part_id])
    
    if check_obj[0] == 0: return (False, -2)
    
    #增加积分 
    si = ScanInfo()
    rst = update_points(user_id, cus_id, c)
    
    #增加积分成功 记录积分
    if rst:
        rst = insert_points_record(cus_id, user_id, chain_part_id, 1, 2, c, 1)
    #积分记录成功返回结果
    if rst:
        #获取签到时间
        now_time = utils.getNowTimeByFormat('%Y-%m-%d %H:%M:%S')
        si.time = now_time
        #查询地址
        sql = 'select name, address from chain_part where id = %s'
        address_obj = mysql.get(sql, [chain_part_id])
        if address_obj != None and len(address_obj) > 0 : 
            name = address_obj[0]
            address = address_obj[1]
            si.address = address
            si.name = name
        si.points_num = c
        si.show_info = '签到成功 积分+' + str(c)
    return (True, si)

#获取首次登陆提示信息
def get_login_info(cus_id):
    rst = []
    sql = '''select member_points, use_app_points, signin_increment_points, comments_increment_points, share_increment_points from points_conf where cus_id = %s'''
    obj = mysql.get(sql, [cus_id])
    if obj == None: return rst
    member_points = obj[0]
    use_app_points = obj[1]
    signin_increment_points = obj[2]
    comments_increment_points = obj[3]
    share_increment_points = obj[4]
    rst.append('成功获取会员卡获%s积分' % member_points)
    rst.append('每日登陆可获取%s积分' % use_app_points)
    rst.append('签到可获%s积分' % signin_increment_points)
    rst.append('评论可获%s积分' % comments_increment_points)
    rst.append('分享可获%s积分' % share_increment_points)
    rst.append('使用积分可换礼兑奖等')
    return rst
        


